﻿#include "ThreadObject.h"

HTHREADPOOL_NAMESPACE_BEGIN

    ThreadObject::ThreadObject(ThreadType type)
    : HThreadObject()
    , m_type(type)
    , m_state(ThreadState::kNew)
    {
    }

    ThreadObject::ThreadObject(ThreadObject && other) noexcept
    : m_type(other.m_type)
    , m_state(other.m_state.load())
    , m_thread(std::move(other.m_thread))
    {
        // 确保源对象处于已移动状态
        other.m_state.store(ThreadState::kTerminated);
        other.m_thread = std::thread();
    }

    ThreadObject& ThreadObject::operator=(ThreadObject&& other) noexcept
    {
        if(this != &other) {
            //先停止当前线程
            quit();
            m_type   = other.m_type;
            m_thread = std::move(other.m_thread);
            m_state  = other.m_state.load();

            other.m_state.store(ThreadState::kTerminated);
            other.m_thread = std::thread();
        }
        return *this;
    }

    ThreadObject::~ThreadObject() { quit(); }

    void ThreadObject::start()
    {
        if(m_state.load() == ThreadState::kNew || m_state.load() == ThreadState::kTerminated) {
            m_state.store(ThreadState::kRunning);
            m_thread = std::thread(&ThreadObject::run, this);  //通过绑定实现多态
        } else if(m_state.load() == ThreadState::kWaiting){
            m_state.store(ThreadState::kRunning);
            m_cv.notify_one();
        }
    }

    void ThreadObject::stop()
    {
        if(m_state.load() == ThreadState::kRunning) {
            m_state.store(ThreadState::kWaiting);
            m_cv.notify_one();  // 唤醒线程以使其暂停
        }
    }

    void ThreadObject::quit()
    {
        if(m_state.load() != ThreadState::kTerminated) {
            m_state.store(ThreadState::kTerminated);
            m_cv.notify_one();
            if(m_thread.joinable()) {
                m_thread.join();
            }
        }
    }

    // 等待线程结束
    void ThreadObject::join()
    {
        if(m_thread.joinable()) {
            m_thread.join();
        }
    }

    bool ThreadObject::isQuit()
    {
        std::lock_guard<std::mutex> lock(m_mutex);
        return m_state == ThreadState::kTerminated;
    }

    ThreadState ThreadObject::state() const { return m_state.load(); }
    ThreadType  ThreadObject::type()
    {
        std::lock_guard<std::mutex> lock(m_mutex);
        return m_type;
    }

HTHREADPOOL_NAMESPACE_END
